<template>
  <div class="all">
    <!-- 最顶部 -->
    <van-nav-bar
        title="商品搜索"
        left-arrow
        @click-left="onClickLeft"
    />
    <!-- 搜索控件 -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
    >
      <template #action>
        <div @click="search(value)">搜索</div>
      </template>
    </van-search>
    <!-- 最近搜索 -->
    <div class="search">
      <div>最近搜索</div>
      <van-icon name="delete-o" @click="delSearch"/>
    </div>
    <div class="searches" v-if="recentSearch.length > 0">
      <div class="recent_search"
      v-for="(item, index) in recentSearch" :key="index"
      @click="search(item)"
      >{{ item }}</div>
    </div>
    <!-- 无搜索 -->
    <div class="no_search" v-else>
      <span>无搜索记录</span>
    </div>
  </div>
</template>

<script>
import { getUserSearch, setUserSearch, delUserSearch } from '@/utils/userSearchLocal.js'
export default {
  data () {
    return {
      value: '',
      recentSearch: getUserSearch() // 最近搜索的内容
    }
  },
  methods: {
    // 存储用户搜索记录
    search (key) {
      // 检测搜索值是否为空
      if (!key) return

      // 添加修改用户搜索记录
      const index = this.recentSearch.indexOf(key)
      if (index !== -1) {
        this.recentSearch.splice(index, 1)
      }
      this.recentSearch.unshift(key)

      // 往本地存储用户搜索记录
      setUserSearch(this.recentSearch)

      // 跳转至搜索详情页面
      this.$router.push(`/searchList?search=${key}`)
    },
    // 删除用户搜索记录
    delSearch () {
      this.recentSearch = []
      delUserSearch()
    },
    // 返回上一页
    onClickLeft () {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
/* 最近搜索 */
.search {
  padding:15px;
  display:flex;
  justify-content:space-between;
}
.searches {
  display:flex;
  flex-wrap:wrap;
  padding:15px;
}
.recent_search {
  width:100px;
  height:30px;
  background:pink;
  text-align: center;
  line-height:30px;
  color:white;
  border-radius: 20px;
  margin-right:5px;
  margin-bottom:5px;
}
/* 无搜索 */
.no_search {
  border-bottom:1px solid gray;
  text-align: center;
}
.no_search span {
  position:relative;
  bottom:-10px;
  background:white;
}
</style>
